import lxml.etree as etree
import json
from urllib import unquote

def readSongs(fil):
    """iTunes XML library file -> generator of songs"""
    tre=etree.parse(fil)
    for udict in tre.getroot(): #tre.getroot is the plist
        for sub in _getDicts(udict):
            for song in _fromInnerDict(sub):
                yield song

def _getDicts(lst):
    """Is used when all we want is the dictionary information and not the
    metadata"""
    return (sub for sub in lst if sub.tag=='dict')

INTERESTING=('Name', 'Artist', 'Album', 'Genre', 'Location', 'Rating',
             'Track Number')

def _fromInnerDict(inner):
    """Extracts the songs from the innermost dict"""
    for val in _getDicts(inner):
        song={}
        for i in xrange(0, len(val), 2):
            if val[i].text in INTERESTING:
                song[val[i].text]=val[i+1].text
        yield _interconvert(song)

def _interconvert(song):
    """Dictionary from iTunes -> dictionary for eleanor"""
    try:
        song['Rating']=str(int(song['Rating'])/20)
    except (KeyError, ValueError):
        pass
    song['Location']=unquote(song['Location'][17:])
    return song

def podcastFilter(songGenerator):
    """Filters podcasts out of the transfer"""
    return (song for song in songGenerator if song['Genre']!='Podcast')

def writeSongs(songGenerator, outFile):
    """Writes the songs into the specified json file"""
    outFile.write(json.dumps(list(podcastFilter(songGenerator)), indent=1))

def main(inFile='C:\Users\Echo\Music\iTunes\iTunes Music Library.xml',
         outFile='newSongs.json'):
    writeSongs(readSongs(inFile), open(outFile, 'w'))


if __name__ == '__main__':
    from sys import argv
    main(*argv[2:])
